import request from "@/base/request";
import TestProblem from "@/types/testProblem";
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import router from "@/router";
import Problem from "@/types/problem";
import Prism from 'prismjs'
import TextInput from "@/types/textInput";
import SaveCache from "@/types/saveCache";

export default function(){
    const isExampath=ref<boolean>(router.currentRoute.value.path.startsWith("/examing"))
    const testProblem=ref<TestProblem>()
    const type=ref<number>(1);

    const index=ref<number>(0);

    const input=ref<TextInput>({
        textId:0,
        inputMap:{}
    })

    const inputMultiple=ref<{ [key: number]: Array<string> }>({})

    const textCache=ref<SaveCache>({
        id:0,
        problemId:0,
        input:""
    })

    const chooseProblem=ref<Problem>();



    async function saveInput(problemId:number,isMutiple:boolean) {
        if(isMutiple){
            let sortedString=Object.values(inputMultiple.value[problemId]).sort((a,b)=>{return a.localeCompare(b)})
            input.value.inputMap[problemId]=sortedString.map(str=>str).join('')
        }

        if(!input.value.inputMap[problemId]){
            return
        }


        textCache.value.problemId=problemId,
        textCache.value.input=input.value.inputMap[problemId]
        let response;
        if(!isExampath.value)response=(await request.post(`/judge/testCache/saveInput`,textCache.value)).data
        else response=(await request.post(`/judge/examCache/saveInput`,textCache.value)).data
        if(response.code===503){
            ElMessage({
                message:`${isExampath.value?"考试":"测验"}已结束`,
                grouping:true,
                type:'warning'
            })
            router.push("/home")
        }else if(response.code!==200){
            ElMessage({
                message:`保存至服务器失败，请重新选择，否则可能会影响成绩计算`,
                grouping:true,
                type:'warning'
            })
            console.log(response.msg)
        }
    }

    async function submitInput() {

        let response
        if(!isExampath.value)response=(await request.post(`/problem/test/submit`,input.value)).data
        else response=(await request.post(`/problem/exam/submit`,input.value)).data
        if(response.code===200){
            ElMessage.success(isExampath.value?"提交成功，考试已结束":"提交成功，稍后可在测验记录查看成绩")
            router.push("/home")
        }else{
            ElMessage({
                message:`状态异常,${response.msg}`,
                grouping:true,
                type:'error'
            })
        }
    }


    async function getTestProblemList(testId:number) {
        try{
            const response= (await request.get(`/problem/test/getProblemListTest/${testId}`)).data
            if(response.code===200){
                if(response.data.remainingTime<=0){
                    ElMessage({
                        message:`测验已结束`,
                        grouping:true,
                        type:'error'
                    })
                    router.push("/home")
                }
                testProblem.value=response.data
        
            }else{
                ElMessage({
                    message:`获取题目列表失败：${response.msg}`,
                    grouping:true,
                    type:'error'
                })
                router.push("/home")
            }
        }catch(error){
            router.push("/home")
        }
    }


    function switchProblem(){
        const mp={
            1:testProblem.value.singleChooseList,
            2:testProblem.value.multipleChooseList,
            3:testProblem.value.fillList,
            4:testProblem.value.judgeList,
            5:testProblem.value.bigList
        }
        chooseProblem.value=mp[type.value][index.value]
        Prism.highlightAll()
        setTimeout(()=>{Prism.highlightAll()},200)
    }

    const getTextType=((index:number,type:number):string=>{
        const mp={
            1:testProblem.value.singleChooseList,
            2:testProblem.value.multipleChooseList,
            3:testProblem.value.fillList,
            4:testProblem.value.judgeList,
            5:testProblem.value.bigList
        }
        const t=input.value.inputMap[mp[type][index].id];
        return t && t.length>0?'success':''
    })


    function nextIndex(v:number){
        let t=index.value+v;
        let type2=type.value
        const mp={
            1:testProblem.value.singleChooseList,
            2:testProblem.value.multipleChooseList,
            3:testProblem.value.fillList,
            4:testProblem.value.judgeList,
            5:testProblem.value.bigList
        }
        if(t>=mp[type.value].length){
            while((++type2)<=5 && !mp[type2])
            type2
            if(type2==6){
                ElMessage({
                    message:`已经是最后一题了`,
                    grouping:true,
                    type:'error'
                })
                return
            }
            type.value=type2
            index.value=0
        }else if(t<0){
            while((--type2)>=0 && !mp[type2])
            type2
            if(type2==-1){
                ElMessage({
                    message:`已经是第一题了`,
                    grouping:true,
                    type:'error'
                })
                return
            }
            type.value=type2
            index.value=mp[type2].length-1
        }else{
            index.value=t
        }
        switchProblem()
    }

    function handleSelect(k1, k2){
        type.value=Number(k2[0])
        index.value=Number(k2[1])
        switchProblem();
    }

    return {textCache,input,chooseProblem,type,testProblem,inputMultiple,getTextType,submitInput,saveInput,nextIndex,getTestProblemList,switchProblem,handleSelect}
}